<HTML>
  <HEAD>

    <TITLE>Search Results</TITLE>
    <meta content="text/html; charset=UTF-8" http-equiv="content-type">

    <link rel="stylesheet" type="text/css" href="css/popupmenu.css" />

    <script type="text/JavaScript" src="js/highlighting.js"> </script>
    <script type="text/JavaScript" src="js/jquery-1.4.3.min.js"> </script>
    <script type="text/JavaScript" src="js/popupmenu.js"> </script>

    <%-- auto compete --%>
    <link rel="stylesheet" href="css/jquery.ui.all.css">
    <script  type="text/JavaScript" src="js/jquery.ui.core.js"></script>
	<script  type="text/JavaScript" src= "js/jquery.ui.widget.js"></script>
	<script  type="text/JavaScript" src="js/jquery.ui.position.js"></script>
	<script  type="text/JavaScript" src="js/jquery.ui.autocomplete.js"></script>

  <script>
    jQuery.noConflict();
	jQuery(function($) {
		
		$("#search" ).autocomplete({
			source: "ajax.jsp"
		});
	});
	</script>

   <%--  auto compete --%>

    <script type="text/JavaScript">


      function preview(myId, format, url, myButton)
      {
        var showFrame =  document.getElementById(myId);
        // get a handle on the <iframe>d document (in a cross-browser way)

        var sty = showFrame.style;
        //alert(showFrame.myshow);
        h = "hr" + "-"+ myId.substring(1);
        document.getElementById(h).style.display="none";
        for (i=1; i<=3; i++) {
          b =  "b" + i + "-"+ myId.substring(1);
          document.getElementById(b).value =
            document.getElementById(b).value.replace("Hide", "Show");

        }
        if (sty.display=='none' || showFrame.myshow != myButton.id) {
          showFrame.src = url;
          sty.display ='block';
          myButton.value='Hide ' + format ;
          showFrame.myshow = myButton.id;
          if (format == "HTML")
            document.getElementById(h).style.display="block";
          //highlightSearchTerms("chapter which is available", false, true, null, null, doc);

        }
        else {
          sty.display='none';
          myButton.value='Show ' + format;
        }
      }

      function hideAll()
      {
        var frm = document.getElementsByTagName("iframe");
        for (i=0; i < frm.length; i++)
        {
          frm[i].style.display = "none";
        }
        var bu = document.getElementsByTagName('button');
        for (i=0; i<bu.length; i++)
        {
          if (bu[i].id.indexOf('b') >=0)
            bu[i].value = bu[i].value.replace('Hide', 'Show');
        }
      }

    </script>


  </HEAD>
  <BODY style="margin-left: 20px">


    <%--
      Licensed to the Apache Software Foundation (ASF) under one or more
      contributor license agreements.  See the NOTICE file distributed with
      this work for additional information regarding copyright ownership.
      The ASF licenses this file to You under the Apache License, Version 2.0
      (the "License"); you may not use this file except in compliance with
      the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
    --%><%@ page import="javax.jcr.Repository,
                 org.apache.jackrabbit.j2ee.RepositoryAccessServlet,
                 org.apache.jackrabbit.util.Text,
                 javax.jcr.Session,
                 javax.jcr.SimpleCredentials,
                 javax.jcr.query.Query,
                 javax.jcr.query.RowIterator,
                 java.text.NumberFormat,
                 javax.jcr.query.Row,
                 javax.jcr.Node,
                 java.net.URLEncoder,
                 java.text.SimpleDateFormat,
                 java.text.DateFormat,
                 java.util.*,

                 javax.jcr.Value,
                 javax.jcr.RepositoryException"%>
    <%@ page contentType="text/html;charset=UTF-8" %><%
        Repository rep;
        Session jcrSession;
        try {
          rep = RepositoryAccessServlet.getRepository(pageContext.getServletContext());
          jcrSession = rep.login(new SimpleCredentials("anonymous", "".toCharArray()));
        } catch (Throwable e) {
    %>Error while accessing the repository: <font color="red"><%= Text.encodeIllegalXMLCharacters(e.getMessage())%></font><br><%
    %>Check the configuration or use the <a href="admin/">easy setup</a> wizard.<%
          return;
        }
        try {
          String wspName = jcrSession.getWorkspace().getName();
          String q = request.getParameter("q");
          if (q == null) {
            q = "";
          } else {
            q = new String(q.getBytes("ISO-8859-1"), "UTF-8");
          }
          if (request.getParameter("as_q") != null) {
            q += " " + new String(request.getParameter("as_q").getBytes("ISO-8859-1"), "UTF-8");
          }
          String executedIn = "";
          String queryTerms = "";
          String totalResults = "";
          long from = 0;
          long to = 10;
          long total = 0;
          long maxPage = 0;
          long minPage = 0;
          long currentPageIndex = 0;
          List indexes = new ArrayList();
          RowIterator rows = null;
          String suggestedQuery = null;
          if (q != null && q.length() > 0) {
            String stmt;
            if (q.startsWith("related:")) {
              String path = q.substring("related:".length());
              stmt = "//element(*, nt:file)[rep:similar(jcr:content, '" + path + "/jcr:content')]/rep:excerpt(.) order by @jcr:score descending";
              queryTerms = "similar to <b>" + Text.encodeIllegalXMLCharacters(path) + "</b>";
            } else {
              queryTerms = "for <b>" + Text.encodeIllegalXMLCharacters(q) + "</b>";
              q = q.replaceAll("'", "''");
              stmt = "//element(*, nt:file)[jcr:contains(jcr:content, '" + q + "')]/rep:excerpt(.) order by @jcr:score descending";
            }
            Query query = jcrSession.getWorkspace().getQueryManager().createQuery(stmt, Query.XPATH);
            
            long time = System.currentTimeMillis();
            rows = query.execute().getRows();
            time = System.currentTimeMillis() - time;
            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(2);
            nf.setMinimumFractionDigits(2);
            executedIn = nf.format(((double) time) / 1000d);
            nf.setMaximumFractionDigits(0);
            totalResults = nf.format(rows.getSize());
            if (request.getParameter("start") != null) {
              from = Long.parseLong(request.getParameter("start"));
              try {
                rows.skip(from);
              } catch (Exception e) {
                // make sure rows are consumed
                while (rows.hasNext()) {
                  rows.nextRow();
                }
              }
            }
            to = Math.min(from + 10, rows.getSize());

            total = rows.getSize();
            maxPage = total / 10L;
            if (total % 10L > 0) {
              maxPage++;
            }
            currentPageIndex = from / 10L;
            maxPage = Math.min(maxPage, currentPageIndex + 10);
            minPage = Math.max(0, currentPageIndex - 10);
            for (long i = minPage; i < maxPage; i++) {
              indexes.add(new Long(i));
            }

            if (total < 10 && !q.startsWith("related:")) {
              try {
                Value v = jcrSession.getWorkspace().getQueryManager().createQuery(
                        "/jcr:root[rep:spellcheck('" + q + "')]/(rep:spellcheck())",
                        Query.XPATH).execute().getRows().nextRow().getValue("rep:spellcheck()");
                if (v != null) {
                  suggestedQuery = v.getString();
                }
              } catch (RepositoryException e) {
                // ignore
              }
            }
          }
          request.setAttribute("title", "Search workspace " + wspName);
    %>
    <div  style="width:800px;">
      <div style="text-align: center">
        <h2 style="color:brown;text-align: center"> <img src="img/logo.png" /> </h2>
        <form name="gs" method="GET">
          <p>
            <input id="search" type="text" name="q" size="41" maxlength="2048" value="<%= Text.encodeIllegalXMLCharacters(q)%>" title="Search">
            <input type=submit value="Search"><br><br>
          </p>
        </form> 
        <% if (rows != null && rows.getSize() == 0) {%>
        <%     if (suggestedQuery != null) {%>
        <p><font class="p" color="#cc0000">Did you mean:</font>
          <a href="viewsearch.jsp?q=<%= Text.encodeIllegalXMLCharacters(suggestedQuery)%>" class="p">
            <b><i><%= Text.encodeIllegalXMLCharacters(suggestedQuery)%></i></b>
          </a><br>
        </p>
        <%     }%>
        <p/>Your search - <b><%= Text.encodeIllegalXMLCharacters(q)%></b> - did not match any documents.
        <br/><br/>Suggestions:
        <ul>
          <li>Make sure all words are spelled correctly.</li>
          <li>Try different keywords.</li>
          <li>Try more general keywords.</li>
          <li>Try fewer keywords.</li>
        </ul>
        <%
         } else if (rows != null) {
        %>
        <table border=0 cellpadding=0 cellspacing=0 width=100% class="t bt">
          <tr>
            <td><font size=-1>Results <b><%= from + 1%></b> - <b><%= to%></b> of about <b><%= totalResults%></b> <%= queryTerms%>. (<b><%= executedIn%></b> seconds) </font></td></tr>
        </table>
        <% if (suggestedQuery != null) {%>
        <p>
          <font class="p" color="#cc0000">Did you mean:</font>
          <a href="viewsearch.jsp?q=<%= Text.encodeIllegalXMLCharacters(suggestedQuery)%>" class="p">
            <b><i><%= Text.encodeIllegalXMLCharacters(suggestedQuery)%></i></b>
          </a><br>
        </p>
        <% }%>

      </div>
      <br/>
      <%
         while (rows.hasNext() && rows.getPosition() < to) {
           Row r = rows.nextRow();
           Node file = (Node) jcrSession.getItem(r.getValue("jcr:path").getString());
           Node resource = file.getNode("jcr:content");
           String size = "";
           if (resource.hasProperty("jcr:data")) {
             double length = resource.getProperty("jcr:data").getLength();
             size = String.valueOf(Math.round(Math.ceil(length / 1000d))) + "k";
           }
           String subject = "";
           if (resource.hasProperty("subject")) {
             subject = resource.getProperty("subject").getString();
           }
           String emailTo = "";
           if (resource.hasProperty("to")) {
             emailTo = resource.getProperty("to").getString();
           }
           String emailFrom = "";
           if (resource.hasProperty("from")) {
             emailFrom = resource.getProperty("from").getString();
           }

           String sent = "";
           if (resource.hasProperty("sent")) {
             sent = resource.getProperty("sent").getString();
           }
           DateFormat df = SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG);
           String lastModified = "";
           if (resource.hasProperty("jcr:lastModified")) {
             lastModified = df.format(resource.getProperty("jcr:lastModified").getDate().getTime());
           }
           String viewURL = Text.encodeIllegalXMLCharacters(request.getContextPath() + "/repository/" + wspName + file.getPath());
      %>
      <B><a href="<%=  viewURL%>" class=l>

          <%= subject.isEmpty() ? Text.encodeIllegalXMLCharacters(file.getName()) + " &nbsp;<img src='../images/doc.jpg' /> <br/>" : "Subject: " + subject + " &nbsp;<img src='../images/email-icon2.gif' /> <br/>"%>
          <%
                     String viewName = Text.encodeIllegalXMLCharacters(request.getContextPath() + "/data" + file.getPath());
                     String path = request.getRequestURL().substring(0, request.getRequestURL().indexOf("/", 10)) + viewName.substring(0, viewName.lastIndexOf("."));
                     String outFileNameNoExt = Text.encodeIllegalXMLCharacters(path) + "-" + resource.getIdentifier();
                     String viewRTF = outFileNameNoExt + ".rtf";
                     String viewHTML = outFileNameNoExt + ".html";
                     String viewPDF = outFileNameNoExt + ".pdf";
                     viewURL = request.getRequestURL().substring(0, request.getRequestURL().indexOf("/", 10)) + viewURL;
                     String tName = file.getName().toLowerCase();
                     /*if (tName.indexOf(".rtf") > 0) {
                       viewRTF = viewURL;
                     } else*/ if (tName.indexOf(".pdf") > 0) {
                       viewPDF = viewURL;
                     } else if (tName.indexOf(".html") > 0 || tName.endsWith(".htm") || tName.endsWith(".mht")) {
                       //viewHTML =  outFileNameNoExt + file.getName().substring(0, tName.lastIndexOf('.')  );
                       viewHTML = viewURL;
                     }

          %>
        </a>
        &nbsp;
        <Button style="height:15px;padding:0;font-size: 50%" id='b1-<%= rows.getPosition()%>'
                onclick=" preview('r<%= rows.getPosition()%>', 'RTF', 'activeX.jsp?url=<%=viewRTF%>&q=<%=q%>', this);">
          Show RTF
        </Button>

        &nbsp;
        <Button style="height:15px;padding:0;font-size: 50%" id='b2-<%= rows.getPosition()%>'
                onclick=" preview('r<%= rows.getPosition()%>', 'HTML', 'activeX.jsp?url=<%=viewHTML%>&q=<%=q%>', this);">
          Show HTML
        </Button>

        &nbsp;
        <Button style="height:15px;padding:0;font-size: 50%" id='b3-<%= rows.getPosition()%>'
                onclick=" preview('r<%= rows.getPosition()%>', 'PDF', 'activeX.jsp?url=<%=viewPDF%>&q=<%=q%>', this);">
          Show PDF
        </Button>

        &nbsp;
        <Button style="height:15px;padding:0;font-size: 50%" id='h4-<%= rows.getPosition()%>'
                onclick="hideAll()">
          Hide All
        </Button>
        &nbsp Tags </B>: <%= buildTags(map, rows.getPosition() + "", null)%>



      <br/>

      <%
                 if (!emailFrom.isEmpty()) {%>
      From:  <%= emailFrom%>    <%= sent%> <br/>
      To: <%= emailTo%> <br/>


      <% }%>
      <%
                 String s = r.getValue("rep:excerpt(jcr:content)").getString();
                 s = s.replace((char) 160, ' ');

      %>

      <%= s%>
      <%-- <%= Text.encodeIllegalXMLCharacters(file.getPath())%> --%>
      - <%= size%> - <%= lastModified%> - <nobr><a href="<%= Text.encodeIllegalXMLCharacters(request.getContextPath())%>/viewsearch.jsp?q=related:<%= Text.encodeIllegalXMLCharacters(URLEncoder.encode(file.getPath(), "UTF-8"))%>">Similar pages</a></nobr>
      <hr id="hr-<%= rows.getPosition()%>" style="display:none" />
      <iframe name="r<%= rows.getPosition()%>" id="r<%= rows.getPosition()%>" src="loading.jsp" frameborder="no" myshow="getit"
              style="display: none;width:100%;height:900px; margin:0px;padding:0px;background-color: gray">

      </iframe>
      <br />
      <br />
      <%
         } // while
      %>
    </div>




    <br clear=all>
    <%
       if (indexes.size() > 1) {
    %>
    <div>
      <table border=0 cellpadding=0 cellspacing=0 align=center>
        <tr>
          <td><font size=-1>Result&nbsp;Page:&nbsp;</font>
            <%
                     if (currentPageIndex != ((Long) indexes.get(0)).longValue()) {
            %><td nowrap align=right><a href=viewsearch.jsp?q=<%= Text.encodeIllegalXMLCharacters(q)%>&start=<%= (currentPageIndex - 1) * 10%>>Previous</a><%
                                 } else {
            %><td nowrap ><font size=-1><%                    }
                     for (Iterator it = indexes.iterator(); it.hasNext();) {
                       long pageIdx = ((Long) it.next()).longValue();
                       if (pageIdx == currentPageIndex) {
              %></font><td nowrap><font size=-1><%= pageIdx + 1%></font><%
                                     } else {
                %><td nowrap><font size=-1><a href=viewsearch.jsp?q=<%= Text.encodeIllegalXMLCharacters(q)%>&start=<%= pageIdx * 10%>><%= pageIdx + 1%></a></font><%
                           }
                         }
                         if (currentPageIndex < (maxPage - 1)) {
            %><td nowrap><font size=-1><a href=viewsearch.jsp?q=<%= Text.encodeIllegalXMLCharacters(q)%>&start=<%= (currentPageIndex + 1) * 10%>>Next</a></font><%
                                     } else {
            %><td nowrap ><%                    }
            %>
      </table>
    </div>
    <%
       }
    %>


    <br clear=all><br>
    <table align="center">
      <tr><td><br><form method=GET action=<%= Text.encodeIllegalXMLCharacters(request.getContextPath())%>/my/viewsearch.jsp>
                        <font size=-1><input type=text name=q size=31 maxlength=2048 value="<%= Text.encodeIllegalXMLCharacters(q)%>" title="Search"> <input type=submit value="Search">
            </font></form>
          <br><font size=-1>
            <a href="<%= Text.encodeIllegalXMLCharacters(request.getContextPath())%>/swr.jsp?q=<%= Text.encodeIllegalXMLCharacters(q)%>&swrnum=<%= rows.getSize()%>">Search&nbsp;within&nbsp;results</a> | <a href="http://issues.apache.org/jira/browse/JCR" target=_blank>Dissatisfied? Help us improve</a></font><br>
          <br>
        </td></tr>
    </table>

    <%
              } // if (rows != null)

              String tableClass = "";
              if (rows != null && rows.getSize() == 0) {
                tableClass = " class=\"t n bt\"";
              }
    %>

    <%--

              // SPELLCHECK('jackrabit') will always evaluate to true
              Query query = jcrSession.getWorkspace().getQueryManager().createQuery("/jcr:root[rep:spellcheck('attachement')]/(rep:spellcheck())", Query.XPATH);

              //.createQuery("SELECT rep:spellcheck() FROM nt:base WHERE jcr:path = '/' AND SPELLCHECK('salt')", Query.SQL);
              rows = query.execute().getRows();
              // the above query will always return the root node no matter what string we check
              if (rows.hasNext()) {
                Row r = rows.nextRow();
                // get the result of the spell checking
                Value v = r.getValue("rep:spellcheck()");
                if (v == null) {
                  out.println("no suggestions");
                  // no suggestion returned, the spelling is correct or the spell checker
                  // does not know how to correct it.
                } else {
                  String suggestion = v.getString();
                  out.println(suggestion);
                }
              }
    --%>


    <%
        } finally {
          if (jcrSession != null) {
            jcrSession.logout();
          }
        }
    %>

   
    <div id="floatMenu">
      <ul class="menu1">
        <li><a href="viewsearch.jsp" onclick="return false;"> Home </a></li>
      </ul>
      <ul class="menu2">
        <li><a href="#" onclick="return false;"> About </a></li>
        <li><a href="#" onclick="return false;"> Support </a></li>
        <li><a href="#" onclick="return false;"> Wiki </a></li>
      </ul>
      <ul class="menu3">
        <li><a href="#" onclick="hideAll(); return false;"> Hide all docs </a></li>
        <li> <a href="upload.jsp"> Upload docs </a></li>
      </ul>
    </div>


  </body>
</html>




<%!    private Map<String, List<String>> map = new HashMap<String, List<String>>() {

    {
      this.put("1", Arrays.asList(new String[]{"tag1", "tag2"}));
      this.put("2", Arrays.asList(new String[]{"tag1", "tag2", "tag3", "tag4"}));
    }
  };

  private String buildTags(Map<String, List<String>> map, String uuid, String user) {
    StringBuilder sb = new StringBuilder();
    List<String> list = map.get(uuid);
    if (list == null) {
      return "";
    }
    for (int i = 0; i < Math.min(3, list.size()); i++) {
      sb.append(list.get(i) + ", ");
    }
    if (list.size() < 3) {
      sb.delete(0, sb.length());
      for (String tag : list) {
        sb.append(" <a  title='right click to search' href='#'>").append(tag).append("</a> &nbsp;");

      }

    } else {
      String link = sb.replace(sb.length() - 2, sb.length(), "...").toString();
      sb.delete(0, sb.length());
      sb.append("<ul id='popmenu-" + uuid + "' class='jqpopupmenu'>");
      for (String tag : list) {
        sb.append("<li><a  title='right click to search' href='#'>").append(tag).append("</a></li>");
      }
      sb.append("</ul>");
      sb.append("<a href='#' data-popupmenu='popmenu-" + uuid + "'>" + link + "</a>");
    }
    sb.append("<input type='text' value='new tag'  onmouseout='this.value=\"new tag\"; this.style.color=\"gray\";' style='width:80px; height:15pt;color:gray' onfocus='this.value=\"\"; this.style.color=\"black\"' /> ");
    return sb.toString();
  }

%>



